#include <iostream>
#include <sstream>
#include <string>
#include <memory>
#include <exception>
#include <jsoncpp/json/json.h>

#include <unistd.h>

using namespace std;

bool deserialize(const std::string &str, Json::Value *out)
{
    Json::CharReaderBuilder crb;
    unique_ptr<Json::CharReader> cr(crb.newCharReader());

    string erro;
    if (!cr->parse(str.c_str(), str.c_str() + str.size(), out, &erro))
    {
        cout << erro << endl;
        return false;
    }

    return true;
}

std::string serialize(const Json::Value &root)
{
    Json::StreamWriterBuilder swb;
    unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());

    std::stringstream out;

    try
    {
        sw->write(root, &out);
    }
    catch (exception &e)
    {
        std::cout << e.what() << std::endl;
        exit(-1);
    }

    return out.str();
}

int main()
{
    Json::Value root_in;
    root_in["name"] = "张三";
    root_in["age"] = 19;
    root_in["sorce"].append(88.8);
    root_in["sorce"].append(46.8);
    root_in["sorce"].append(79.3);

    std::string ser = serialize(root_in);
    std::cout << "序列化结果：\n"
              << ser << endl;

    Json::Value root_out;
    deserialize(ser, &root_out);

    std::cout << "反序列化结果：\n"
              << "name:" << root_out["name"].asString() << endl
              << "age:" << root_out["age"].asInt() << endl
              << "sorce: " << root_out["sorce"][0].asDouble() << ", " << root_out["sorce"][1].asUInt() << ", " << root_out["sorce"][2].asFloat() << endl;

    return 0;
}